﻿using NineSeas.ViewModels;
using Orchard.Security;
using Orchard.ContentManagement;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using NineSeas.Models;
using System.Net.Http;
using Orchard.Users.Events;
using NineSeas.Extensions;
using System.Net;

namespace NineSeas.Api
{
    [Authorize]
    public class AccountController: ApiController
    {
        private readonly IAuthenticationService _authenticationService;
        private readonly IMembershipService _membershipService;
        private readonly IUserEventHandler _userEventHandler;
        public AccountController(IAuthenticationService authenticationService,
            IMembershipService membershipService,
            IUserEventHandler userEventHandler)
        {
            _authenticationService = authenticationService;
            _membershipService = membershipService;
            _userEventHandler = userEventHandler;
        }

        #region Actions
        [HttpPost]
        [AllowAnonymous]
        [ActionName("SignIn")]
        public HttpResponseMessage SignIn(SignInViewModel viewModel)
        {
            var validationResults = new List<MessageDefinition>();
            var user = ValidateLogOn(viewModel.Username, viewModel.Password, validationResults);

            if (!validationResults.Any(m => m.Type == MessageDefinitions.Types.Error))
            {
                _authenticationService.SignIn(user, viewModel.RememberMe);
                _userEventHandler.LoggedIn(user);

                return Request.CreateResponse<AuthorProfileViewModel>(HttpStatusCode.Accepted, Get());
            }
            else
            {
                return Request.CreateResponse<GeneralResult>(HttpStatusCode.Conflict, new GeneralResult
                {
                    Code = validationResults.Select(m => m.Code),
                    Message = String.Empty
                });
            }
        }

        [HttpGet]
        [AllowAnonymous]
        public HttpResponseMessage SignOut()
        {
            var wasLoggedInUser = _authenticationService.GetAuthenticatedUser();
            _authenticationService.SignOut();
            if (wasLoggedInUser != null)
                _userEventHandler.LoggedOut(wasLoggedInUser);

            return Request.CreateResponse<GeneralResult>(HttpStatusCode.Accepted, new GeneralResult
            {
                Code = new List<int>() {MessageDefinitions.NORMAL.Code},
                Message = String.Empty
            });
        }

        [HttpGet]
        public AuthorProfileViewModel Get()
        {
            var user = _authenticationService.GetAuthenticatedUser();
            var profile = user.As<AuthorProfilePart>();

            return AuthorProfileViewModel.FromPart(profile);
        }
        #endregion

        #region Private Methods
        private IUser ValidateLogOn(string userNameOrEmail, string password, IList<MessageDefinition> validationResults)
        {
            bool validate = true;

            if (String.IsNullOrEmpty(userNameOrEmail))
            {
                validationResults.Add(MessageDefinitions.SIGNIN_USERNAME_REQUIRED);
                validate = false;
            }
            if (String.IsNullOrEmpty(password))
            {
                validationResults.Add(MessageDefinitions.SIGNIN_PASSWORD_REQUIRED);
                validate = false;
            }

            if (!validate)
                return null;

            var user = _membershipService.ValidateUser(userNameOrEmail, password);
            if (user == null)
            {
                validationResults.Add(MessageDefinitions.SIGNIN_FAILED);
            }

            return user;
        }
        #endregion
    }
}